package com.ibeetl.cms.web;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.entity.Message;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.MessageService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.BuyHouseSubsidies;
import com.ibeetl.cms.entity.EssentialInformation;
import com.ibeetl.cms.entity.Sincerity;
import com.ibeetl.cms.entity.TelentCard;
import com.ibeetl.cms.service.*;
import com.ibeetl.cms.util.BusinessTypeConstant;
import com.ibeetl.cms.util.ProcessConstant;
import com.ibeetl.cms.util.RoleConstant;
import com.ibeetl.cms.web.quer3.BuyHouseSubsidiesQueryCheck;
import com.ibeetl.cms.web.query.BuyHouseSubsidiesQuery;
import com.ibeetl.cms.web.query2.BuyHouseSubsidiesQueryCompany;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * BuyHouseSubsidies控制器
 * 购房补贴
 * @author likai
 * @date 2018/9/26
 */
@Controller
public class BuyHouseSubsidiesController {

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/buyHouseSubsidies";


    @Autowired
    private BuyHouseSubsidiesService buyHouseSubsidiesService;

    @Autowired
    private MessageService messageService;

    @Autowired
    CorePlatformService platformService;

    @Autowired
    private EssentialInformationService essentialInformationService;

    @Autowired
    private BusinessProcessService businessProcessService;

    @Autowired
    FileService fileService;

    @Autowired
    private SincerityService sincerityService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    TelentCardService telentCardService;

    @Autowired
    private PretrialService pretrialService;

    @Autowired
    private DeclareLimitService declareLimitService;

    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("buyHouseSubsidies")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/buyHouseSubsidies/index.html");
        view.addObject("search", BuyHouseSubsidiesQuery.class.getName());
        return view;
    }

    /**
     * 查看页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/findenterprise.do")
    @ResponseBody
    public ModelAndView findenterprise(Integer id) {
        ModelAndView view = new ModelAndView("/cms/buyHouseSubsidies/findenterpriseedit.html");
        BuyHouseSubsidies buyHouseSubsidies = buyHouseSubsidiesService.queryById(id);
        view.addObject("look", true);
        view.addObject("buyHouseSubsidies", buyHouseSubsidies);
        return view;
    }


    @GetMapping(MODEL + "/edit.do")
    @Function("buyHouseSubsidies")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/buyHouseSubsidies/edit.html");
        BuyHouseSubsidies buyHouseSubsidies = buyHouseSubsidiesService.queryById(id);
        CoreUser currentUser = platformService.getCurrentUser();
        Long userId = currentUser.getId();
        view.addObject("Startdate",telentCardService.findStartCard(userId).getStartdate());
        view.addObject("buyHouseSubsidies", buyHouseSubsidies);
        return view;
    }

    @PostMapping(MODEL + "/terminal.do")
    @Function(value = "buyHouseSubsidies", name = "个人购房补贴申报终止")
    @ResponseBody
    public JsonResult<String> terminalDo(Integer id) {
        /**
         * 更改状态为终止
         */
        BuyHouseSubsidies buyHouseSubsidies = buyHouseSubsidiesService.queryById(id);
        buyHouseSubsidies.setBusinessStateCode(ProcessConstant.TERMINIATE);
        buyHouseSubsidies.setBusinessState(ProcessConstant.TERMINIATE_STR);
        boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);

        /**
         * 流程信息
         */
        processInformation(buyHouseSubsidies);

        if (success) {
            return JsonResult.success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    @GetMapping(MODEL + "/view.do")
    @Function("buyHouseSubsidies")
    @ResponseBody
    public ModelAndView view(Integer id) {
        ModelAndView view = new ModelAndView("/cms/buyHouseSubsidies/view.html");
        BuyHouseSubsidies buyHouseSubsidies = buyHouseSubsidiesService.queryById(id);
        view.addObject("buyHouseSubsidies", buyHouseSubsidies);
        return view;
    }

    /**
     * 新增申报时的校验
     *
     * @return
     */
    @PostMapping(MODEL + "/addCheck.json")
    @Function("buyHouseSubsidies")
    @ResponseBody
    public JsonResult<Map<String, String>> addCheck() {
        Map<String, String> result = new HashMap<>(4);
        result.put("successFlag", "0");
        result.put("message", "industry talent card expire");
        return JsonResult.success(result);
    }

    /**
     * 新增时引入个人基本信息
     *
     * @return
     */
    @GetMapping(MODEL + "/add.do")
    @Function("buyHouseSubsidies")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/buyHouseSubsidies/add.html");
        CoreUser currentUser = platformService.getCurrentUser();
        Long userId = currentUser.getId();
        EssentialInformation essentialInformation = essentialInformationService.finduserid(userId);
        view.addObject("Startdate",telentCardService.findStartCard(userId).getStartdate());
        view.addObject("essentialInformation", essentialInformation);

        /**
         * 新增时读取，以后不变
         */
        TelentCard card = telentCardService.findCard(userId);
        view.addObject("card", card);
        return view;
    }


    /**
     * 只能看到属于自己的记录
     *
     * @param condtion
     * @return
     */
    @PostMapping(MODEL + "/list.json")
    @Function(value = "buyHouseSubsidies", name = "个人查看购房补贴申报")
    @ResponseBody
    public JsonResult<PageQuery> list(BuyHouseSubsidiesQuery condtion) {

        CoreUser user = platformService.getCurrentUser();
        long userId = user.getId();
        condtion.setDeclareUserId(userId);
        if (condtion.getYear() == "" || condtion.getYear() == null) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }

        PageQuery page = condtion.getPageQuery();
        buyHouseSubsidiesService.queryByCondition(page);
        return JsonResult.success(page);
    }

    /**
     * 增加申报的逻辑
     *
     * @param buyHouseSubsidies
     * @return
     */
    @PostMapping(MODEL + "/add.json")
    @Function(value = "buyHouseSubsidies", name = "新增购房补贴申报")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class) BuyHouseSubsidies buyHouseSubsidies) {
        buyHouseSubsidies.setBusinessStateCode(ProcessConstant.WAIT_APPLICATION);
        buyHouseSubsidies.setBusinessState(ProcessConstant.WAIT_APPLICATION_STR);
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        String yearStr = year.toString();
        buyHouseSubsidies.setYear(yearStr);
        buyHouseSubsidies.setCreationDate(new Date());

        /**
         * 设置declare_user_id, declare_user_name, company_id,
         * TODO organization_code
         */
        CoreUser currentUser = platformService.getCurrentUser();
        Long userId = currentUser.getId();
        EssentialInformation essentialInformation = essentialInformationService.finduserid(userId);
        buyHouseSubsidies.setDeclareUserId(Math.toIntExact(userId));
        buyHouseSubsidies.setDeclareUserName(essentialInformation.getName());
        buyHouseSubsidies.setCompanyId(essentialInformation.getCompanyId());


        buyHouseSubsidiesService.save(buyHouseSubsidies);

        /**
         * 增加流程信息
         */
        processInformation(buyHouseSubsidies);

        return new JsonResult().success();
    }

    /**
     * 保存并申报的逻辑
     *
     * @param buyHouseSubsidies
     * @return
     */
    @PostMapping(MODEL + "/addAndDeclare.json")
    @Function(value = "buyHouseSubsidies", name = "新增购房补贴并申报")
    @ResponseBody
    public JsonResult addAndDeclare(@Validated(ValidateConfig.ADD.class) BuyHouseSubsidies buyHouseSubsidies) {
        if(Float.parseFloat(buyHouseSubsidies.getCardScore())< 30){
            return JsonResult.failMessage("积分不足30无法提交申报");
        }
        buyHouseSubsidies.setBusinessStateCode(ProcessConstant.TO_COMPANY);
        buyHouseSubsidies.setBusinessState(ProcessConstant.TO_COMPANY_STR);
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        String yearStr = year.toString();
        buyHouseSubsidies.setYear(yearStr);
        buyHouseSubsidies.setCreationDate(new Date());
        buyHouseSubsidies.setDeclareTime(new Date());


        /**
         * 设置declare_user_id, declare_user_name, company_id,
         * TODO organization_code
         */
        CoreUser currentUser = platformService.getCurrentUser();
        Long userId = currentUser.getId();
        EssentialInformation essentialInformation = essentialInformationService.finduserid(userId);
        buyHouseSubsidies.setDeclareUserId(Math.toIntExact(userId));
        buyHouseSubsidies.setDeclareUserName(essentialInformation.getName());
        buyHouseSubsidies.setCompanyId(essentialInformation.getCompanyId());

        buyHouseSubsidiesService.save(buyHouseSubsidies);

        /**
         * 增加流程信息
         */
        processInformation(buyHouseSubsidies);

        return new JsonResult().success();
    }

    /**
     * 更新申报时的逻辑
     *
     * @param buyHouseSubsidies
     * @return
     */
    @PostMapping(MODEL + "/update.json")
    @Function(value = "buyHouseSubsidies", name = "更改购房补贴申报")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class) BuyHouseSubsidies buyHouseSubsidies) {
        boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 更新并申报
     *
     * @param buyHouseSubsidies
     * @return
     */
    @PostMapping(MODEL + "/updateAndDeclare.json")
    @Function(value = "buyHouseSubsidies", name = "更新并申报购房补贴申报")
    @ResponseBody
    public JsonResult<String> updateAndDeclare(@Validated(ValidateConfig.UPDATE.class) BuyHouseSubsidies buyHouseSubsidies) {
        /**
         * 更改状态已申报
         */

        buyHouseSubsidies.setBusinessStateCode(ProcessConstant.TO_COMPANY);
        buyHouseSubsidies.setBusinessState(ProcessConstant.TO_COMPANY_STR);
        buyHouseSubsidies.setDeclareTime(new Date());

        boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);

//        processInformation(buyHouseSubsidies);

        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }


    @GetMapping(MODEL + "/view.json")
    @Function("buyHouseSubsidies")
    @ResponseBody
    public JsonResult<BuyHouseSubsidies> queryInfo(Integer id) {
        BuyHouseSubsidies buyHouseSubsidies = buyHouseSubsidiesService.queryById(id);
        return JsonResult.success(buyHouseSubsidies);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function(value = "buyHouseSubsidies", name = "删除个人购房补贴申报")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        buyHouseSubsidiesService.batchDelBuyHouseSubsidies(idList);
        return JsonResult.success();
    }


    /**
     * 从这开始是企业的代码
     */


    @GetMapping(MODEL + "/company.do")
    @Function("buyHouseSubsidies.company")
    @ResponseBody
    public ModelAndView company() {
        ModelAndView view = new ModelAndView("/cms/buyHouseSubsidies/companyIndex.html");
        view.addObject("search", BuyHouseSubsidiesQueryCompany.class.getName());
        return view;
    }

    @PostMapping(MODEL + "/companyList.json")
    @Function(value = "buyHouseSubsidies.company", name = "企业查看购房补贴申请")
    @ResponseBody
    public JsonResult<PageQuery> companyList(BuyHouseSubsidiesQuery condition) {
        /**
         * 只能看到自己的记录
         */
        CoreUser user = platformService.getCurrentUser();
        long userId = user.getId();
        condition.setCompanyId(userId);
        if (condition.getBusinessStateCode() == null || "".equalsIgnoreCase(condition.getBusinessStateCode())) {
            condition.setBusinessStateCode(ProcessConstant.TO_COMPANY);

        }

        PageQuery page = condition.getPageQuery();
        buyHouseSubsidiesService.findenterprise(page);
        return JsonResult.success(page);
    }

    /**
     * 跳转到受理页面
     *
     * @param id
     * @return
     */
    @GetMapping(MODEL + "/deal.do")
    @Function("buyHouseSubsidies.company")
    @ResponseBody
    public ModelAndView deal(Integer id) {
        ModelAndView view = new ModelAndView("/cms/buyHouseSubsidies/deal.html");
        BuyHouseSubsidies buyHouseSubsidies = buyHouseSubsidiesService.queryById(id);
        view.addObject("buyHouseSubsidies", buyHouseSubsidies);
        return view;
    }

    /**
     ** 功能描述:企业终止功能
     ** @author liujun
     ** @date 2020/5/7 14:40
     **/
    @PostMapping(MODEL + "/terminal.json")
    @Function("buyHouseSubsidies.company")
    @ResponseBody
    public JsonResult<String> terminal(@Validated(ValidateConfig.UPDATE.class) BuyHouseSubsidies buyHouseSubsidies) {
        //业务受理时间验证
        if(declareLimitService.isInTime(CommonController.getIntType("buy_house_subsidies"),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }
        /**
         * 更改状态为终止
         */
        buyHouseSubsidies.setBusinessStateCode(ProcessConstant.TERMINIATE);
        buyHouseSubsidies.setBusinessState(ProcessConstant.TERMINIATE_STR);
        buyHouseSubsidies.setProcessResult(ProcessConstant.COMPANY_TERMINIATE_STR);

        Boolean postResult =
                pretrialService.post(AppInterfaceType.BUY_HOUSE_SUBSIDIES_TYPE, buyHouseSubsidies.getExternalTaskId(), "2", "", "", buyHouseSubsidies.getHandlingSuggestion(), "0");

        if (postResult) {
            boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);
            /**
             * 流程信息
             */
            processInformation(buyHouseSubsidies);
            if (success) {
                //调用增加业务流程数据
                businessProcessService.processInformation(buyHouseSubsidies.getId(), ProcessConstant.TERMINIATE_STR, ProcessConstant.TERMINIATE, buyHouseSubsidies.getHandlingSuggestion(), ProcessConstant.COMPANY_TERMINIATE_STR, BusinessTypeConstant.BUYHOUSE);
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        } else {
            return JsonResult.failMessage("提供人社预审处理结果接口调用异常");
        }
    }

    /**
     ** 功能描述:企业退回功能
     ** @author liujun
     ** @date 2019/10/14 16:47
     **/
    @PostMapping(MODEL + "/back.json")
    @Function("buyHouseSubsidies.company")
    @ResponseBody
    public JsonResult<String> back(@Validated(ValidateConfig.UPDATE.class) BuyHouseSubsidies buyHouseSubsidies) {
        //业务受理时间验证
        if(declareLimitService.isInTime(CommonController.getIntType("buy_house_subsidies"),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }
        /**
         * 更改状态为退回
         */
        buyHouseSubsidies.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
        buyHouseSubsidies.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
        buyHouseSubsidies.setProcessResult(ProcessConstant.COMPANY_BACK_STR);

        boolean postResult = pretrialService.post(AppInterfaceType.BUY_HOUSE_SUBSIDIES_TYPE, buyHouseSubsidies.getExternalTaskId(), "1", "", "", buyHouseSubsidies.getHandlingSuggestion(), "1");

        if (postResult) {
            boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);

            processInformation(buyHouseSubsidies);
            if (success) {
                //调用增加业务流程数据
                businessProcessService.processInformation(buyHouseSubsidies.getId(), ProcessConstant.COMPANY_BACK_STR, ProcessConstant.COMPANY_BACK, buyHouseSubsidies.getHandlingSuggestion(), ProcessConstant.COMPANY_BACK_STR, BusinessTypeConstant.BUYHOUSE);

                //给企业发一条退回信息
                Message message = new Message();
                message.setCompanyId(buyHouseSubsidies.getCompanyId());
                message.setUserId(buyHouseSubsidies.getUserId());
                message.setStatus(-1);
                message.setContent(buyHouseSubsidies.getHandlingSuggestion());
                message.setType(Integer.parseInt(BusinessTypeConstant.BUYHOUSE));
                message.setCreateDate(new Date());
                messageService.save(message);
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        } else {
            return JsonResult.failMessage("提供人社预审处理结果接口调用异常");

        }

    }

    /**
     ** 功能描述:企业受理功能
     ** @author liujun
     ** @date 2020/5/7 14:40
     **/
    @PostMapping(MODEL + "/pass.json")
    @Function("buyHouseSubsidies.company")
    @ResponseBody
    public JsonResult<String> pass(@Validated(ValidateConfig.UPDATE.class) BuyHouseSubsidies buyHouseSubsidies) {
        //业务受理时间验证
        if(declareLimitService.isInTime(CommonController.getIntType("buy_house_subsidies"),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }

        /**
         * 更改状态为通过
         */
        buyHouseSubsidies.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
        buyHouseSubsidies.setBusinessState(ProcessConstant.TO_FIRSTCHECK_STR);
        buyHouseSubsidies.setProcessResult(ProcessConstant.COMPANY_ADOPT_STR);
        buyHouseSubsidies.setCompanyDeclareTime(new Date());

        boolean postResult = pretrialService.post(AppInterfaceType.BUY_HOUSE_SUBSIDIES_TYPE, buyHouseSubsidies.getExternalTaskId(), "0", buyHouseSubsidies.getDeclareMoney().toString(), "元", buyHouseSubsidies.getHandlingSuggestion(), "0");

        if (postResult) {
            boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);
            processInformation(buyHouseSubsidies);
            if (success) {
                //调用增加业务流程数据
                businessProcessService.processInformation(buyHouseSubsidies.getId(), ProcessConstant.COMPANY_ADOPT_STR, ProcessConstant.COMPANY_ADOPT, buyHouseSubsidies.getHandlingSuggestion(), ProcessConstant.COMPANY_ADOPT_STR, BusinessTypeConstant.BUYHOUSE);
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        } else {
            return JsonResult.failMessage("提供人社预审处理结果接口调用异常");
        }
    }

    /**
     * 初审代码
     *
     * @return
     */

    @GetMapping(MODEL + "/firstcheck.do")
    @Function("buyHouseSubsidies.check")
    @ResponseBody
    public ModelAndView firstcheck(String year) {
        ModelAndView view = new ModelAndView("/cms/buyHouseSubsidies/firstcheck.html");
        BuyHouseSubsidiesQuery condtion = new BuyHouseSubsidiesQuery();

        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condtion.setYear(year);
        view.addObject("year", year);

        /**
         * 获取本年度所有有申报的公司
         */
        condtion.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
        List<BuyHouseSubsidies> lists = buyHouseSubsidiesService.queryCompany(condtion);
        List<Map<String, Object>> companies = new ArrayList<>(16);

        for (BuyHouseSubsidies buyHouseSubsidies : lists) {
            if(buyHouseSubsidies.getCompanyId() == null){
                continue;
            }
            Map<String, Object> item = new HashMap<>(8);
            int  waitCheckNumber = firstCheckNumber(Long.valueOf(buyHouseSubsidies.getCompanyId()), "TODO",year);
            int  allCheckNumber = firstCheckNumber(Long.valueOf(buyHouseSubsidies.getCompanyId()), "ALL",year);
            if(waitCheckNumber == 0){
                //无待审核记录 不展示企业
                continue;
            }
            item.put("companyId", buyHouseSubsidies.getCompanyId());
            item.put("companyName", buyHouseSubsidies.getCurrentWorkingEnterprise());
            item.put("waitCheckNumber", waitCheckNumber);
            item.put("allCheckNumber", allCheckNumber);
            companies.add(item);
        }
        view.addObject("companies", companies);
        view.addObject("search", BuyHouseSubsidiesQueryCheck.class.getName());

        return view;
    }

    /**
     * 获得本年度已办任务
     */
    @PostMapping(MODEL + "/firstcheckList.json")
    @ResponseBody
    public JsonResult<PageQuery> firstcheckList(BuyHouseSubsidiesQuery condtion) {
        CoreUser user = platformService.getCurrentUser();
        long userId = user.getId();
        condtion.setProcessUserId(userId);
        condtion.setBusinessType(BusinessTypeConstant.BUYHOUSE);

        /**
         * 获得本年度已办任务
         */
        if (condtion.getYear() == "" || condtion.getYear() == null) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }
        PageQuery page = condtion.getPageQuery();
        buyHouseSubsidiesService.queryDoneTask(page);
        return JsonResult.success(page);
    }

    /**
     * 获取初审的数量 获取待初审的数量,type = 'TODO'
     */
    private int firstCheckNumber(Long companyId, String type,String year) {
        BuyHouseSubsidiesQuery condition = new BuyHouseSubsidiesQuery();
        condition.setCompanyId(companyId);

        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condition.setYear(year);

        List<String> ids = new ArrayList();
        if ("TODO".equalsIgnoreCase(type)) {
            ids.add(ProcessConstant.COMPANY_ADOPT_STR);
            ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        } else {
            ids.add(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
            ids.add(ProcessConstant.FIRSTCHECK_STR);
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
            ids.add(ProcessConstant.COMPANY_ADOPT_STR);
            ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        }

        condition.setIds(ids);
        int size = buyHouseSubsidiesService.queryEmployeesCount(condition);
        return size;
    }

    /**
     * 获取待复审的数量 type = 'TODO',
     * 复审总数量 type = 'ALL'
     */
    private int finalCheckNumber(Long companyId, String type,String year) {
        /**
         * 获取待初审的数量,type = 'TODO'
         */

        BuyHouseSubsidiesQuery condition = new BuyHouseSubsidiesQuery();
        condition.setCompanyId(companyId);

        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condition.setYear(year);

        List<String> ids = new ArrayList();
        if ("TODO".equalsIgnoreCase(type)) {
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        } else {
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
            ids.add(ProcessConstant.FINALCHECK_TERMINIATE_STR);
            ids.add(ProcessConstant.FINALCHECK_BACK_STR);
            ids.add(ProcessConstant.FINALCHECK_ADOPT_STR);
        }

        condition.setIds(ids);
        int size = buyHouseSubsidiesService.queryEmployeesCount(condition);
        return size;
    }
        /**
         * 获取该申报，该公司下的员工
         *
         * @param companyId
         * @return
         */
        @PostMapping(MODEL + "/employees.json")
        @Function("buyHouseSubsidies.check")
        @ResponseBody
        public JsonResult<PageQuery> employees (Long companyId,String year){
            BuyHouseSubsidiesQuery condtion = new BuyHouseSubsidiesQuery();
            condtion.setCompanyId(companyId);

            if(StringUtils.isEmpty(year)){
                Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
                year = yearNum.toString();
            }
            condtion.setYear(year);

            List<String> ids = new ArrayList();
            ids.add(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
            ids.add(ProcessConstant.FIRSTCHECK_STR);
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
            ids.add(ProcessConstant.COMPANY_ADOPT_STR);
            ids.add(ProcessConstant.FINALCHECK_BACK_STR);
            condtion.setIds(ids);
            PageQuery page = condtion.getPageQuery();
            buyHouseSubsidiesService.queryEmployees(page);
            return JsonResult.success(page);
        }

        @GetMapping(MODEL + "/firstcheckEdit.do")
        @Function("buyHouseSubsidies.check")
        @ResponseBody
        public ModelAndView firstcheckEdit (Integer id){
            ModelAndView view = new ModelAndView("/cms/buyHouseSubsidies/firstcheckEdit.html");
            BuyHouseSubsidies buyHouseSubsidies = buyHouseSubsidiesService.queryById(id);
            view.addObject("buyHouseSubsidies", buyHouseSubsidies);
            String bStateCode = buyHouseSubsidies.getBusinessStateCode();
            if(!bStateCode.equals(ProcessConstant.TO_FIRSTCHECK)){
                view.addObject("look",true);
            }
            return view;
        }


        @PostMapping(MODEL + "/firstcheckTerminal.json")
        @Function("buyHouseSubsidies.check")
        @ResponseBody
        public JsonResult<String> firstcheckTerminal (@Validated(ValidateConfig.UPDATE.class) BuyHouseSubsidies
        buyHouseSubsidies){
            /**
             * 更改状态为终止
             */
            buyHouseSubsidies.setBusinessStateCode(ProcessConstant.TERMINIATE);
            buyHouseSubsidies.setBusinessState(ProcessConstant.TERMINIATE_STR);
            buyHouseSubsidies.setProcessResult(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
            boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);

            processInformation(buyHouseSubsidies);

            if (success) {
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        }

        @PostMapping(MODEL + "/firstcheckBack.json")
        @Function("buyHouseSubsidies.check")
        @ResponseBody
        public JsonResult<String> firstcheckBack (@Validated(ValidateConfig.UPDATE.class) BuyHouseSubsidies
        buyHouseSubsidies){
            /**
             * 更改状态为退回
             */
            buyHouseSubsidies.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
            buyHouseSubsidies.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
            buyHouseSubsidies.setProcessResult(ProcessConstant.FIRSTCHECK_STR);
            boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);

            processInformation(buyHouseSubsidies);

            if (success) {
                //给企业发一条退回信息
                Message message = new Message();
                message.setCompanyId(buyHouseSubsidies.getCompanyId());
                message.setUserId(buyHouseSubsidies.getUserId());
                message.setStatus(-1);
                message.setContent(buyHouseSubsidies.getHandlingSuggestion());
                message.setType(Integer.parseInt(BusinessTypeConstant.BUYHOUSE));
                message.setCreateDate(new Date());
                messageService.save(message);
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        }

        @PostMapping(MODEL + "/firstcheckPass.json")
        @Function("buyHouseSubsidies.check")
        @ResponseBody
        public JsonResult<String> firstcheckPass (@Validated(ValidateConfig.UPDATE.class) BuyHouseSubsidies
        buyHouseSubsidies){
            String businessType = "3";
            List<Sincerity> sincerityList = sincerityService.blacklist(buyHouseSubsidies.getUserId(), buyHouseSubsidies.getCompanyId(), businessType);
            if (null != sincerityList && sincerityList.size() > 0) {
                //用户或用户所属企业已进入黑名单
                for (Sincerity sincerity : sincerityList) {
                    if (sincerity.getType().equals(Long.toString(RoleConstant.PERSON))) {
                        //个人
                        return JsonResult.failMessage(buyHouseSubsidies.getName() + "在黑名单中有记录");
                    } else if (sincerity.getType().equals(Long.toString(RoleConstant.COMPANY))) {
                        //企业
                        String name = enterpriseService.findenterprise(buyHouseSubsidies.getCompanyId()).getEnterpriseName();
                        return JsonResult.failMessage(name + "公司在黑名单中有记录");
                    }
                }
            }
            /**
             * 更改状态为待复审
             */
            buyHouseSubsidies.setBusinessStateCode(ProcessConstant.TO_FINALCHECK);
            buyHouseSubsidies.setBusinessState(ProcessConstant.TO_FINALCHECK_STR);
            buyHouseSubsidies.setProcessResult(ProcessConstant.FIRSTCHECK_ADOPT_STR);
            boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);

            processInformation(buyHouseSubsidies);
            if (success) {
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        }

       /**
         * 复审代码
         */

        @GetMapping(MODEL + "/finalcheck.do")
        @Function("buyHouseSubsidies.review")
        @ResponseBody
        public ModelAndView finalcheck(String year) {
            ModelAndView view = new ModelAndView("/cms/buyHouseSubsidies/finalcheck.html");
            BuyHouseSubsidiesQuery condtion = new BuyHouseSubsidiesQuery();
            if(StringUtils.isEmpty(year)) {
                Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
                year = yearNum.toString();
            }
            condtion.setYear(year);
            view.addObject("year", year);

            /**
             * 获取本年度所有有申报的公司
             */
            condtion.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
            List<BuyHouseSubsidies> lists = buyHouseSubsidiesService.queryCompany(condtion);
            List<Map<String, Object>> companies = new ArrayList<>(16);

            for (BuyHouseSubsidies buyHouseSubsidies : lists) {
                if(buyHouseSubsidies.getCompanyId() == null){
                    continue;
                }
                Map<String, Object> item = new HashMap<>(8);
                int waitCheckNumber = finalCheckNumber(Long.valueOf(buyHouseSubsidies.getCompanyId()), "TODO",year);
                if(waitCheckNumber == 0){
                    continue;
                }
                int allCheckNumber = finalCheckNumber(Long.valueOf(buyHouseSubsidies.getCompanyId()), "ALL",year);
                item.put("companyId", buyHouseSubsidies.getCompanyId());
                item.put("companyName", buyHouseSubsidies.getCurrentWorkingEnterprise());
                item.put("waitCheckNumber", waitCheckNumber);
                item.put("allCheckNumber", allCheckNumber);
                companies.add(item);
            }
            view.addObject("companies", companies);
            view.addObject("search", BuyHouseSubsidiesQueryCheck.class.getName());
            return view;
        }

        /**
         * 获取该申报，该公司下的员工
         *
         * @param companyId
         * @return
         */
        @PostMapping(MODEL + "/finalcheckEmployees.json")
        @Function("buyHouseSubsidies.review")
        @ResponseBody
        public JsonResult<PageQuery> finalcheckEmployees (Long companyId,String year){
            BuyHouseSubsidiesQuery condtion = new BuyHouseSubsidiesQuery();
            condtion.setCompanyId(companyId);

            if(StringUtils.isEmpty(year)) {
                Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
                year = yearNum.toString();
            }
            condtion.setYear(year);

            List<String> ids = new ArrayList();
            ids.add(ProcessConstant.FINALCHECK_TERMINIATE_STR);
            ids.add(ProcessConstant.FINALCHECK_BACK_STR);
            ids.add(ProcessConstant.FINALCHECK_ADOPT_STR);
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
            condtion.setIds(ids);
            PageQuery page = condtion.getPageQuery();
            buyHouseSubsidiesService.queryEmployees(page);
            return JsonResult.success(page);
        }

        @GetMapping(MODEL + "/finalcheckEdit.do")
        @Function("buyHouseSubsidies.review")
        @ResponseBody
        public ModelAndView finalcheckEdit (Integer id){
            ModelAndView view = new ModelAndView("/cms/buyHouseSubsidies/finalcheckEdit.html");
            BuyHouseSubsidies buyHouseSubsidies = buyHouseSubsidiesService.queryById(id);
            view.addObject("buyHouseSubsidies", buyHouseSubsidies);
            String bStateCode = buyHouseSubsidies.getBusinessStateCode();
            if(!bStateCode.equals(ProcessConstant.TO_FINALCHECK)){
                view.addObject("look",true);
            }
            return view;
        }


        @PostMapping(MODEL + "/finalcheckTerminal.json")
        @Function("buyHouseSubsidies.review")
        @ResponseBody
        public JsonResult<String> finalcheckTerminal (@Validated(ValidateConfig.UPDATE.class) BuyHouseSubsidies
        buyHouseSubsidies){
            /**
             * 更改状态为终止
             */
            buyHouseSubsidies.setBusinessStateCode(ProcessConstant.TERMINIATE);
            buyHouseSubsidies.setBusinessState(ProcessConstant.TERMINIATE_STR);
            buyHouseSubsidies.setProcessResult(ProcessConstant.FINALCHECK_TERMINIATE_STR);
            boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);

            processInformation(buyHouseSubsidies);

            if (success) {
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        }

        @PostMapping(MODEL + "/finalcheckBack.json")
        @Function("buyHouseSubsidies.review")
        @ResponseBody
        public JsonResult<String> finalcheckBack (@Validated(ValidateConfig.UPDATE.class) BuyHouseSubsidies
        buyHouseSubsidies){
            /**
             * 更改状态为退回
             */
            buyHouseSubsidies.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
            buyHouseSubsidies.setBusinessState(ProcessConstant.TO_FIRSTCHECK_STR);
            buyHouseSubsidies.setProcessResult(ProcessConstant.FINALCHECK_BACK_STR);
            boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);


            processInformation(buyHouseSubsidies);
            if (success) {
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        }

        @PostMapping(MODEL + "/finalcheckPass.json")
        @Function("buyHouseSubsidies.review")
        @ResponseBody
        public JsonResult<String> finalcheckPass (@Validated(ValidateConfig.UPDATE.class) BuyHouseSubsidies
        buyHouseSubsidies){
            /**
             * 更改状态为生效
             */
            buyHouseSubsidies.setBusinessStateCode(ProcessConstant.DONE);
            buyHouseSubsidies.setBusinessState(ProcessConstant.DONE_STR);
            buyHouseSubsidies.setProcessResult(ProcessConstant.FINALCHECK_ADOPT_STR);
            boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);

            processInformation(buyHouseSubsidies);
            if (success) {
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        }


        @PostMapping(MODEL + "/batchFinalCheckPass.json")
        @Function("buyHouseSubsidies.review")
        @ResponseBody
        public JsonResult<String> batchFinalCheckPass (String ids,String year){
            /**
             * 更改状态为生效
             */
            List<Long> idList = ConvertUtil.str2longs(ids);
            for (Long id : idList) {
                /**
                 * 获得这个公司id下所有待复审的业务
                 */
                BuyHouseSubsidiesQuery condtion = new BuyHouseSubsidiesQuery();

                if(StringUtils.isEmpty(year)) {
                    Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
                    year = yearNum.toString();
                }
                condtion.setYear(year);
                condtion.setCompanyId(id);

                List<String> params = new ArrayList();
                params.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
                condtion.setIds(params);
                PageQuery page = condtion.getPageQuery();
                page.setPageSize(Integer.MAX_VALUE);
                buyHouseSubsidiesService.queryEmployees(page);
                List<BuyHouseSubsidies> buyHouseSubsidiesList = page.getList();

                for (BuyHouseSubsidies b : buyHouseSubsidiesList) {
                    passHelper(b);
                }
            }
            return JsonResult.success();
        }

        private void passHelper (BuyHouseSubsidies buyHouseSubsidies){
            buyHouseSubsidies.setBusinessStateCode(ProcessConstant.DONE);
            buyHouseSubsidies.setBusinessState(ProcessConstant.DONE_STR);
            buyHouseSubsidies.setProcessResult(ProcessConstant.FINALCHECK_ADOPT_STR);
            buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);
            processInformation(buyHouseSubsidies);
        }
        /**
         * 共用的插入流程信息的方法
         */
        private void processInformation (BuyHouseSubsidies buyHouseSubsidies){
            businessProcessService.processInformation(buyHouseSubsidies.getId(),
                    buyHouseSubsidies.getBusinessState(),
                    buyHouseSubsidies.getBusinessStateCode(),
                    buyHouseSubsidies.getHandlingSuggestion(),
                    buyHouseSubsidies.getProcessResult(),
                    BusinessTypeConstant.BUYHOUSE);
        }
    }
